package com.juc.future;

import java.util.concurrent.*;

/**
 * @Author Zan
 * @Create 2024/5/6 19:58
 * @ClassName : FutureThreadPoolDemo
 * @Description : TODO 请用一句话描述该类的功能
 */
public class FutureThreadPoolDemo {
    public static void main(String[] args) throws Exception {
        // 三个任务，目前开启多个异步任务线程来处理，请问耗时多少

        // 不进行new对象（new对象都需要进行GC垃圾回收，占用内存），使用线程池技术
        ExecutorService threadPool = Executors.newFixedThreadPool(3); // 这个线程池里有三个线程

        long startTime = System.currentTimeMillis();

        FutureTask<String> futureTask1 = new FutureTask<String>(() -> {
            try { TimeUnit.MILLISECONDS.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); }
            return "task1 over";
        });
        threadPool.submit(futureTask1);

        FutureTask<String> futureTask2 = new FutureTask<String>(() -> {
            try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
            return "task2 over";
        });
        threadPool.submit(futureTask2);

        FutureTask<String> futureTask3 = new FutureTask<String>(() -> {
            try { TimeUnit.MILLISECONDS.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); }
            return "task3 over";
        });
        threadPool.submit(futureTask3);

        // get获取数据
        System.out.println(futureTask1.get());
        System.out.println(futureTask2.get());
        System.out.println(futureTask3.get());

        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: " + (endTime - startTime) + " 毫秒");
        System.out.println(Thread.currentThread().getName() + "\t -----end");

        threadPool.shutdown();

        /*Thread a1 = new Thread(futureTask1, "a1");
        a1.start();*/

    }

    private static void m1() {
        // 三个任务，目前只有一个线程main来处理，请问耗时多少
        long startTime = System.currentTimeMillis();
        // 暂停毫秒
        try {
            TimeUnit.MILLISECONDS.sleep(500);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }
        try { TimeUnit.MILLISECONDS.sleep(300); } catch (InterruptedException e) { e.printStackTrace(); }

        long endTime = System.currentTimeMillis();
        System.out.println("----costTime: " + (endTime - startTime) + " 毫秒");

        System.out.println(Thread.currentThread().getName() + "\t -----end");
    }
}
